package com.crawler.util;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author guorui1
 */
@Slf4j
public class StreamKit {
    /**
     * 流数据的拷贝
     */
    public static void copy(InputStream in, OutputStream out) throws IOException {
        int read;
        byte[] buffer = new byte[1024 * 1024];
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }

    /**
     * 将一个输入流，读成字符串
     */
    public static String stm2String(InputStream in, String charset) throws IOException {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            copy(in, out);
            return out.toString(charset);
        }
    }

    public static byte[] toByteArray(InputStream in) throws IOException {
        return toByteArray(in, true);
    }

    public static byte[] toByteArray(InputStream in, boolean ignoreException) throws IOException {
        byte[] tmp = new byte[1024];
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try {
            int read;
            while ((read = in.read(tmp)) != -1) {
                buffer.write(tmp, 0, read);
            }
        } catch (IOException e) {
            if (!ignoreException) {
                throw e;
            } else {
                log.debug(e.getMessage(), e);
            }
        }
        return buffer.toByteArray();
    }
}
